<template>
  <div class="double-menu-container">
    <!-- 一级菜单 -->
    <div class="first-level-menu">
      <div
        v-for="route in menuRoutes"
        :key="route.path"
        :class="['menu-item', { active: activeFirstMenu === route.path }]"
        @click="handleFirstMenuClick(route)"
        @mouseenter="(e) => handleMenuHover(route, e)"
        @mouseleave="handleMenuLeave"
      >
        <div class="menu-icon">
          <component v-if="route.meta?.icon" :is="Icons[route.meta.icon]" />
        </div>
        <div class="menu-title">{{ route.meta?.title }}</div>
      </div>
    </div>

    <!-- 二级菜单 - 展开模式 -->
    <div 
      class="second-level-menu" 
      v-if="!appStore.collapsed && currentChildren.length > 0"
    >
      <div
        v-for="child in currentChildren"
        :key="getFullPath(activeFirstMenu, child.path)"
        :class="['sub-menu-item', { active: selectedPath === getFullPath(activeFirstMenu, child.path) }]"
        @click="handleSubMenuClick(child)"
      >
        <component 
          v-if="child.meta?.icon" 
          :is="Icons[child.meta.icon]" 
          class="sub-menu-icon"
        />
        <span class="sub-menu-title">{{ child.meta?.title }}</span>
      </div>
    </div>

    <!-- 二级菜单 - 折叠模式（悬浮弹出） -->
    <Transition name="submenu-fade">
      <div 
        v-if="appStore.collapsed && showPopupMenu && popupChildren.length > 0"
        class="popup-menu"
        :style="popupStyle"
        @mouseenter="handlePopupEnter"
        @mouseleave="handlePopupLeave"
      >
        <div class="popup-menu-title">{{ popupTitle }}</div>
        <div
          v-for="child in popupChildren"
          :key="getFullPath(popupParentPath, child.path)"
          :class="['popup-menu-item', { active: selectedPath === getFullPath(popupParentPath, child.path) }]"
          @click="handlePopupMenuClick(child)"
        >
          <component 
            v-if="child.meta?.icon" 
            :is="Icons[child.meta.icon]" 
            class="popup-menu-icon"
          />
          <span class="popup-menu-text">{{ child.meta?.title }}</span>
        </div>
      </div>
    </Transition>
  </div>
</template>

<script setup>
import { ref, watch, computed } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { routes } from '@/router/routes'
import * as Icons from '@ant-design/icons-vue'
import { useAppStore } from '@/store'

const router = useRouter()
const route = useRoute()
const appStore = useAppStore()

const activeFirstMenu = ref('')
const selectedPath = ref('')

// 弹出菜单相关状态
const showPopupMenu = ref(false)
const popupChildren = ref([])
const popupParentPath = ref('')
const popupTitle = ref('')
const popupStyle = ref({})
let hideTimer = null

// 检测是否为移动端
const isMobile = () => {
  return window.innerWidth <= 768
}

// 菜单路由（过滤掉登录页等基础路由）
const menuRoutes = computed(() => {
  const processedRoutes = []
  
  routes.forEach(item => {
    if (item.meta?.hidden || item.path === '/login' || item.path === '/404' || item.path.includes('*')) {
      return
    }
    
    // 如果有children
    if (item.children && item.children.length > 0) {
      const visibleChildren = item.children.filter(child => !child.meta?.hidden)
      
      // 只有一个子路由，将子路由提升到一级菜单
      if (visibleChildren.length === 1) {
        const child = visibleChildren[0]
        processedRoutes.push({
          path: item.path === '/' ? `/${child.path}` : `${item.path}/${child.path}`.replace(/\/+/g, '/'),
          name: child.name,
          meta: child.meta,
          children: [],
          originalPath: item.path,
          childPath: child.path
        })
      } 
      // 有多个子路由，保留父级和子级结构
      else if (visibleChildren.length > 1) {
        processedRoutes.push({
          path: item.path,
          name: item.name,
          meta: item.meta,
          children: visibleChildren,
          hasMultipleChildren: true
        })
      }
    }
    // 没有children的路由
    else if (item.meta) {
      processedRoutes.push({
        path: item.path,
        name: item.name,
        meta: item.meta,
        children: []
      })
    }
  })
  
  return processedRoutes
})

// 当前选中一级菜单的子菜单
const currentChildren = computed(() => {
  const currentRoute = menuRoutes.value.find(item => item.path === activeFirstMenu.value)
  // 只有当明确标记为有多个子菜单时才返回子菜单列表
  if (currentRoute?.hasMultipleChildren && currentRoute?.children) {
    return currentRoute.children.filter(child => !child.meta?.hidden)
  }
  return []
})

// 获取完整路径
const getFullPath = (parentPath, childPath) => {
  if (childPath.startsWith('/')) {
    return childPath
  }
  const fullPath = `${parentPath}/${childPath}`.replace(/\/+/g, '/')
  return fullPath
}

// 点击一级菜单
const handleFirstMenuClick = (route) => {
  activeFirstMenu.value = route.path
  
  // 如果有多个子菜单，默认选中第一个
  if (route.hasMultipleChildren && route.children && route.children.length > 0) {
    const firstChild = route.children[0]
    const fullPath = getFullPath(route.path, firstChild.path)
    selectedPath.value = fullPath
    router.push(fullPath)
  } else {
    // 如果没有子菜单或只有一个子菜单，直接跳转
    selectedPath.value = route.path
    router.push(route.path)
    
    // 移动端自动关闭菜单
    if (isMobile() && !appStore.collapsed) {
      appStore.toggleCollapsed()
    }
  }
}

// 点击二级菜单
const handleSubMenuClick = (child) => {
  const fullPath = getFullPath(activeFirstMenu.value, child.path)
  selectedPath.value = fullPath
  router.push(fullPath)
  
  // 移动端自动关闭菜单
  if (isMobile() && !appStore.collapsed) {
    appStore.toggleCollapsed()
  }
}

// 鼠标悬停在一级菜单上（折叠模式下显示弹出菜单）
const handleMenuHover = (route, event) => {
  if (!appStore.collapsed) return
  
  // 清除隐藏计时器
  if (hideTimer) {
    clearTimeout(hideTimer)
    hideTimer = null
  }

  // 如果有多个子菜单，显示弹出菜单
  if (route.hasMultipleChildren && route.children && route.children.length > 0) {
    popupChildren.value = route.children.filter(child => !child.meta?.hidden)
    popupParentPath.value = route.path
    popupTitle.value = route.meta?.title || ''
    
    // 计算弹出位置（在一级菜单右侧）
    const menuItem = event.currentTarget
    const rect = menuItem.getBoundingClientRect()
    popupStyle.value = {
      top: `${rect.top}px`,
      left: `${rect.right}px`
    }
    
    showPopupMenu.value = true
  } else {
    showPopupMenu.value = false
  }
}

// 鼠标离开一级菜单
const handleMenuLeave = () => {
  if (!appStore.collapsed) return
  
  // 延迟隐藏，给用户时间移动到弹出菜单上
  hideTimer = setTimeout(() => {
    showPopupMenu.value = false
  }, 200)
}

// 鼠标进入弹出菜单
const handlePopupEnter = () => {
  if (hideTimer) {
    clearTimeout(hideTimer)
    hideTimer = null
  }
}

// 鼠标离开弹出菜单
const handlePopupLeave = () => {
  showPopupMenu.value = false
}

// 点击弹出菜单项
const handlePopupMenuClick = (child) => {
  const fullPath = getFullPath(popupParentPath.value, child.path)
  selectedPath.value = fullPath
  activeFirstMenu.value = popupParentPath.value
  router.push(fullPath)
  showPopupMenu.value = false
  
  // 移动端自动关闭菜单
  if (isMobile() && !appStore.collapsed) {
    appStore.toggleCollapsed()
  }
}

// 根据当前路由更新菜单状态
const updateMenuStatus = (path) => {
  // 从处理后的菜单路由中查找匹配项
  for (const menuRoute of menuRoutes.value) {
    // 精确匹配
    if (menuRoute.path === path) {
      activeFirstMenu.value = menuRoute.path
      selectedPath.value = path
      return
    }
    
    // 检查子菜单
    if (menuRoute.hasMultipleChildren && menuRoute.children) {
      for (const child of menuRoute.children) {
        const fullPath = getFullPath(menuRoute.path, child.path)
        if (fullPath === path) {
          activeFirstMenu.value = menuRoute.path
          selectedPath.value = fullPath
          return
        }
      }
    }
  }
  
  // 如果没有精确匹配，尝试从路由matched中查找
  const matched = route.matched
  if (matched.length > 1) {
    const parentRoute = matched[matched.length - 2]
    // 在菜单中查找对应的父级路由
    const menuParent = menuRoutes.value.find(m => m.path === parentRoute.path)
    if (menuParent) {
      activeFirstMenu.value = menuParent.path
      selectedPath.value = path
    }
  }
}

// 监听路由变化
watch(
  () => route.path,
  (newPath) => {
    updateMenuStatus(newPath)
  },
  { immediate: true }
)

// 监听二级菜单变化，更新 store 状态（只在非折叠状态下影响布局）
watch(
  currentChildren,
  (children) => {
    // 只在非折叠状态下，二级菜单才会影响侧边栏宽度
    if (!appStore.collapsed) {
      appStore.setShowSubMenu(children.length > 0)
    }
  },
  { immediate: true }
)

// 监听折叠状态变化
watch(
  () => appStore.collapsed,
  (collapsed) => {
    if (collapsed) {
      // 折叠时，关闭弹出菜单
      showPopupMenu.value = false
      // 折叠时不显示二级菜单区域
      appStore.setShowSubMenu(false)
    } else {
      // 展开时，根据当前菜单是否有子菜单来决定
      appStore.setShowSubMenu(currentChildren.value.length > 0)
    }
  }
)
</script>

<style lang="scss" scoped>
.double-menu-container {
  display: flex;
  flex: 1;
  height: 100%;
  overflow: hidden;
}

// 一级菜单样式
.first-level-menu {
  width: 80px;
  background: var(--bg-color);
  display: flex;
  flex-direction: column;
  overflow-y: auto;
  overflow-x: hidden;
  border-right: 1px solid var(--border-color);

  .menu-item {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    padding: 16px 8px;
    cursor: pointer;
    transition: all 0.3s;
    color: var(--text-color-secondary);
    position: relative;
    border-bottom: 1px solid var(--border-color);

    &:hover {
      background: var(--hover-bg);
      color: #1890ff;
    }

    &.active {
      background: #1890ff;
      color: #fff;
    }

    .menu-icon {
      font-size: 20px;
      margin-bottom: 8px;
      
      :deep(svg) {
        width: 20px;
        height: 20px;
      }
    }

    .menu-title {
      font-size: 12px;
      text-align: center;
      line-height: 1.2;
      word-break: break-all;
      width: 100%;
    }
  }
}

// 二级菜单样式
.second-level-menu {
  flex: 1;
  background: var(--bg-color);
  border-right: 1px solid var(--border-color);
  overflow-y: auto;
  overflow-x: hidden;
  min-width: 160px;

  .sub-menu-item {
    display: flex;
    align-items: center;
    padding: 14px 20px;
    cursor: pointer;
    transition: all 0.3s;
    color: var(--text-color);

    &:hover {
      background: var(--hover-bg);
      color: #1890ff;
    }

    &.active {
      background: var(--active-bg);
      color: #1890ff;
    }

    .sub-menu-icon {
      font-size: 16px;
      margin-right: 12px;
      
      :deep(svg) {
        width: 16px;
        height: 16px;
      }
    }

    .sub-menu-title {
      font-size: 14px;
      flex: 1;
    }
  }
}

// 手机端适配 - 保持左右布局结构
@media screen and (max-width: 768px) {
  .first-level-menu {
    .menu-item {
      padding: 12px 8px;

      .menu-icon {
        font-size: 18px;
        margin-bottom: 6px;
        
        :deep(svg) {
          width: 18px;
          height: 18px;
        }
      }

      .menu-title {
        font-size: 11px;
      }
    }
  }

  .second-level-menu {
    .sub-menu-item {
      padding: 12px 16px;

      .sub-menu-icon {
        font-size: 14px;
        margin-right: 10px;
        
        :deep(svg) {
          width: 14px;
          height: 14px;
        }
      }

      .sub-menu-title {
        font-size: 13px;
      }
    }
  }
}

// 弹出菜单样式（折叠模式）
.popup-menu {
  position: fixed;
  background: var(--popup-bg);
  box-shadow: 0 2px 8px var(--shadow-color);
  border-radius: 4px;
  min-width: 160px;
  max-width: 200px;
  max-height: 400px;
  overflow-y: auto;
  z-index: 1001;
  padding: 4px 0;
  border: 1px solid var(--border-color);

  .popup-menu-title {
    padding: 8px 16px;
    font-size: 14px;
    font-weight: 500;
    color: var(--text-color);
    border-bottom: 1px solid var(--border-color);
    margin-bottom: 4px;
  }

  .popup-menu-item {
    display: flex;
    align-items: center;
    padding: 10px 16px;
    cursor: pointer;
    transition: all 0.3s;
    color: var(--text-color);

    &:hover {
      background: var(--menu-item-hover-bg);
      color: #1890ff;
    }

    &.active {
      background: var(--active-bg);
      color: #1890ff;
    }

    .popup-menu-icon {
      font-size: 14px;
      margin-right: 10px;
      
      :deep(svg) {
        width: 14px;
        height: 14px;
      }
    }

    .popup-menu-text {
      font-size: 14px;
      flex: 1;
    }
  }

  &::-webkit-scrollbar {
    width: 6px;
  }

  &::-webkit-scrollbar-thumb {
    background: rgba(0, 0, 0, 0.2);
    border-radius: 3px;

    &:hover {
      background: rgba(0, 0, 0, 0.3);
    }
  }

  &::-webkit-scrollbar-track {
    background: transparent;
  }
}

// 弹出菜单动画
.submenu-fade-enter-active,
.submenu-fade-leave-active {
  transition: opacity 0.2s, transform 0.2s;
}

.submenu-fade-enter-from {
  opacity: 0;
  transform: translateX(-10px);
}

.submenu-fade-leave-to {
  opacity: 0;
  transform: translateX(-10px);
}

// 滚动条样式
.first-level-menu,
.second-level-menu {
  &::-webkit-scrollbar {
    width: 6px;
    height: 6px;
  }

  &::-webkit-scrollbar-thumb {
    background: rgba(0, 0, 0, 0.2);
    border-radius: 3px;

    &:hover {
      background: rgba(0, 0, 0, 0.3);
    }
  }

  &::-webkit-scrollbar-track {
    background: transparent;
  }
}
</style>

